<template>
    <div class="app-container">

        <div class="filter-container">
            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="分类名称" v-model="listQuery.searchName">
            </el-input>

            <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="分类ID" v-model="listQuery.searchId" @keypress='validateNumber($event)'>
            </el-input>

            <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">搜索</el-button>
            <el-button class="filter-item" type="warning" icon="delete2" @click="resetQuery">重置</el-button>
            <el-button class="filter-item" style="margin-left: 20px;" @click="handleCreate" type="primary" icon="edit">新建分类</el-button>
            <el-button class='filter-item' type="primary" icon="document" @click="handleDownload">导出excel</el-button>
        </div>

        <el-table :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit highlight-current-row :row-class-name="tableRowClassName">
            <el-table-column align="center" label='分类ID' width="95">
                <template scope="scope">
                    {{scope.row.id}}
                </template>
            </el-table-column>
            <el-table-column label="URL" align="center" width="250">
                <template scope="scope">
                    <span>{{scope.row.id | fontUrl(scope.row.randId, '/category')}}</span>
                </template>
            </el-table-column>
            <el-table-column label="分类名称" align="center">
                <template scope="scope">
                    <el-input v-show="scope.row.editing" size="small" v-model="scope.row.newName" @keyup.enter.native="commitUpdate(scope.row)" @keyup.esc.native="scope.row.editing=false"></el-input>
                    <span v-show="!scope.row.editing" @click="scope.row.editing=true" style="display: inline-block; width: 100%;">{{scope.row.name}}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" width="200">
                <template scope="scope">
                    <span>{{scope.row.createTime|parseTime}}</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center">
                <template scope="scope">
                    <span>{{scope.row.status === 0 ? '下架':'上架'}}</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200">
                <template scope="scope">
                    <el-button class="filter-item" type="primary" size="small" icon="edit" @click="handleEdit(scope.row.id)">编辑</el-button>
                    <el-button v-if="scope.row.status === 1" size="small" type="danger" @click="toggle(scope.row, 0)">下架</el-button>
                    <el-button v-if="scope.row.status === 0" size="small" type="success" @click="toggle(scope.row, 1)">上架</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div v-show="!listLoading" class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
                           :page-sizes="[10,20,30,50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
            </el-pagination>
        </div>
    </div>
</template>

<script>
    import { getList, toggleStatus, update } from '@/api/category';
    import { parseTime } from '@/filters/index';

    var defaultListQuery = {
        page: 1,
        pageSize: 20,
        searchName: '',
        searchId: '',
        orderKey: 'ID_DESC'
    }
    export default {
        data() {
            var listQuery = JSON.parse(JSON.stringify(defaultListQuery));
            var listQueryJson = sessionStorage.getItem(this.$route.path.replace(/\//g, '_'));
            if (listQueryJson) {
                listQuery = JSON.parse(listQueryJson);
            }
            return {
                list: null,
                total: null,
                listQuery: listQuery,
                listLoading: true,
                selectedRowID: sessionStorage.getItem(this.$route.path.replace(/\//g, '_') + '_selected_row_id')
            }
        },
        created() {
            this.getList();
        },
        methods: {
            resetQuery() {
                this.listQuery = JSON.parse(JSON.stringify(defaultListQuery));
                this.selectedRowID = '';
                sessionStorage.removeItem(this.$route.path.replace(/\//g, '_') + '_selected_row_id')
                this.getList();
            },
            tableRowClassName(row) {
                if (this.selectedRowID && row.id == this.selectedRowID) {
                    return 'sstt-selected-row';
                }
            },
            getList() {
                if (this.checkParamError()) {
                    this.$message({
                        title: '参数错误',
                        message: this.checkParamError(),
                        type: 'error',
                        duration: 1000
                    });
                    return;
                }
                this.listLoading = true;
                getList(this.listQuery).then(response => {
                    this.list = response.data.data.map(v => {
                        v.editing = false;
                        v.newName = v.name;
                        return v;
                    });
                    this.total = response.data.totalCount;
                    this.listLoading = false;
                    sessionStorage.setItem(this.$route.path.replace(/\//g, '_'), JSON.stringify(this.listQuery));
                }).catch(err => {
                    console.log(err);
                    this.listLoading = false;
                });
            },
            handleFilter() {
                this.getList();
            },
            handleCreate() {
                this.$router.push('/category/add');
            },
            handleEdit(id) {
                sessionStorage.setItem(this.$route.path.replace(/\//g, '_') + '_selected_row_id', id)
                this.$router.push('/category/update/' + id);
            },
            toggle(item, status) {
                toggleStatus(item.id, status).then(() => {
                    this.$notify({
                        title: '成功',
                        message: '更新状态成功',
                        type: 'success',
                        duration: 2000
                    });
                    item.status = status;
                }).catch(err => {
                    console.log(err)
                });
            },
            commitUpdate(item) {
                item.editing = false;
                if (item.newName.length > 16 || item.newName.length < 2) {
                    this.$message({
                        title: '错误',
                        message: '分类名字符长度在2到16位',
                        type: 'error',
                        duration: 2000
                    });
                    return;
                }
                if (item.newName !== item.name) {
                    const orgName = item.name;
                    item.name = item.newName;
                    update(item).then(() => {
                        this.$notify({
                            title: '成功',
                            message: '更新成功',
                            type: 'success',
                            duration: 2000
                        });
                    }).catch(err => {
                        console.log(err)
                        this.$message({
                            title: '失败',
                            message: '原因:' + err.msg,
                            type: 'error',
                            duration: 2000
                        });
                        item.name = orgName;
                    });
                }
            },
            handleSizeChange(val) {
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.page = val;
                this.getList();
            },
            handleDownload() {
                if (this.checkParamError()) {
                    this.$message({
                        title: '参数错误',
                        message: this.checkParamError(),
                        type: 'error',
                        duration: 1000
                    });
                    return;
                }
                const copyQuery = JSON.parse(JSON.stringify(this.listQuery));
                copyQuery.page = 1;
                copyQuery.pageSize = 1000;
                getList(copyQuery).then(response => {
                    const dataList = response.data.data;
                    require.ensure([], () => {
                        const { export_json_to_excel } = require('@/vendor/Export2Excel');
                        dataList.forEach(item => {
                            item.url = 'http://120.25.249.44/category/' + item.id;
                            item.createTime = parseTime(item.createTime);
                            item.status = item.status ? '上架' : '下架';
                        });
                        const tHeader = ['分类ID', 'URL', '分类名称', '创建时间', '状态'];
                        const filterVal = ['id', 'url', 'name', 'createTime', 'status'];
                        const data = this.formatJson(filterVal, dataList);
                        export_json_to_excel(tHeader, data, '分类列表');
                    })
                }).catch(err => {
                    console.log(err)
                });
            },
            formatJson(filterVal, jsonData) {
                return jsonData.map(v => filterVal.map(j => v[j]))
            },
            validateNumber(event) {
                var isNumber = event.charCode >= 48 && event.charCode <= 57
                var res = isNumber && this.phone.length < 21;
                if (!res) {
                    event.preventDefault();
                }
                return res;
            },
            checkParamError() {
                if (this.listQuery.searchId && !/^\d*$/.test(this.listQuery.searchId)) {
                    return '分类ID必须是数字';
                }
                return '';
            }
        }
    };
</script>